package com.bsoft.gol.hcb.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author impel
 * @Date 2021/5/26 15:19
 * @Description:
 * @Version 1.0
 */
public class BeanUtil extends BeanUtils{
    private static  Map<String,Map<String,Field>> cacheMap = new HashMap<>();

    /**
     * 忽略大小写copy
     * @param source
     * @param target
     * @param <T>
     * @return
     */

    public static<T>T copyPropertiesIgnoreCase(Object source,Object target){
        Map<String,Field>sourceMap=getFieldMap(source.getClass());
        getFieldMap(target.getClass()).values().forEach((it)->{
            Field field=sourceMap.get(it.getName().toLowerCase().replace("_",""));
            if(field!=null){
                it.setAccessible(true);
                field.setAccessible(true);
                try{
                    if(field.get(source)!=null&& StringUtils.isBlank(field.get(source).toString()))
                        it.set(target,field.get(source));
                }catch(IllegalAccessException e){
                    e.printStackTrace();
                }
            }
        });
        return(T)target;
    }

    /**
     *
     * @param clazz
     * @return
     */
    private static Map<String,Field>getFieldMap(Class clazz){
        Map<String,Field>result=cacheMap.get(clazz.getName());
        if(result==null){
            synchronized(clazz){
                if(result==null){
                    Map<String,Field>fieldMap=new HashMap<>();
                    for(Field field:clazz.getDeclaredFields()){
                        fieldMap.put(field.getName().toLowerCase().replace("_",""),field);
                    }
                    cacheMap.put(clazz.getName(),fieldMap);
                    result=cacheMap.get(clazz.getName());
                }
            }
        }
        return result;
    }

}
